const express = require('express');
const router = express.Router();
const pool = require('../config/database');

// 根据ISBN获取图书
router.get('/:isbn', async (req, res) => {
  console.log('Searching book with ISBN:', req.params.isbn);
  
  try {
    const [results] = await pool.query(
      'SELECT * FROM books WHERE isbn = ?', 
      [req.params.isbn]
    );
    
    if (results.length === 0) {
      console.log('Book not found with ISBN:', req.params.isbn);
      res.status(404).json({ error: 'Book not found' });
      return;
    }
    
    console.log('Book found:', results[0]);
    res.json(results[0]);
  } catch (err) {
    console.error('Error fetching book:', err);
    res.status(500).json({ error: err.message });
  }
});

// 获取所有图书
router.get('/', async (req, res) => {
  console.log('Fetching all books');
  
  try {
    const [results] = await pool.query('SELECT * FROM books ORDER BY id DESC');
    console.log(`Found ${results.length} books`);
    res.json(results);
  } catch (err) {
    console.error('Error fetching books:', err);
    res.status(500).json({ error: err.message });
  }
});

// 添加图书
router.post('/', async (req, res) => {
  const book = req.body;
  console.log('Received book data:', book);

  // 数据验证
  if (!book.isbn || !book.title) {
    console.error('Invalid book data:', book);
    res.status(400).json({ error: 'ISBN and title are required' });
    return;
  }

  // 确保数值字段为数字类型
  if (book.purchase_discount) {
    book.purchase_discount = parseFloat(book.purchase_discount);
  }
  if (book.sales_discount) {
    book.sales_discount = parseFloat(book.sales_discount);
  }
  if (book.price) {
    book.price = parseFloat(book.price);
  }
  if (book.quantity) {
    book.quantity = parseInt(book.quantity);
  }

  // 如果有经销商ID，验证经销商是否存在
  if (book.dealer_id) {
    const [dealerResults] = await pool.query(
      'SELECT id FROM dealers WHERE id = ?',
      [book.dealer_id]
    );

    if (dealerResults.length === 0) {
      console.error('Dealer not found:', book.dealer_id);
      res.status(400).json({ error: 'Invalid dealer ID' });
      return;
    }

    // 经销商存在，继续添加图书
    await insertBook(book);
  } else {
    // 没有经销商ID，直接添加图书
    await insertBook(book);
  }

  async function insertBook(bookData) {
    try {
      const [result] = await pool.query('INSERT INTO books SET ?', bookData);
      console.log('图书添加成功:', result);
      
      // 查询刚刚添加的图书信息
      const [bookInfo] = await pool.query('SELECT * FROM books WHERE id = ?', [result.insertId]);
      
      res.json({ 
        success: true,
        message: '图书添加成功',
        data: {
          id: result.insertId,
          title: bookInfo[0].title,
          isbn: bookInfo[0].isbn,
          quantity: bookInfo[0].quantity
        }
      });
    } catch (err) {
      console.error('Error adding book:', err);
      if (err.code === 'ER_DUP_ENTRY') {
        res.status(400).json({ 
          success: false,
          message: 'ISBN已存在',
          error: 'ISBN already exists' 
        });
      } else {
        res.status(500).json({ 
          success: false,
          message: '添加图书失败',
          error: err.message 
        });
      }
    }
  }
});

// 更新图书
router.put('/:id', async (req, res) => {
  const book = req.body;
  console.log('Attempting to update book:', req.params.id, book);

  try {
    const [result] = await pool.query(
      'UPDATE books SET ? WHERE id = ?',
      [book, req.params.id]
    );
    if (result.affectedRows === 0) {
      console.log('Book not found for update:', req.params.id);
      res.status(404).json({ error: 'Book not found' });
      return;
    }
    res.json({ message: 'Book updated successfully' });
  } catch (err) {
    console.error('Error updating book:', err);
    res.status(500).json({ error: err.message });
  }
});

// 删除图书
router.delete('/:id', async (req, res) => {
  console.log('Attempting to delete book:', req.params.id);

  try {
    const [result] = await pool.query(
      'DELETE FROM books WHERE id = ?',
      [req.params.id]
    );
    if (result.affectedRows === 0) {
      console.log('Book not found for deletion:', req.params.id);
      res.status(404).json({ error: 'Book not found' });
      return;
    }
    res.json({ message: 'Book deleted successfully' });
  } catch (err) {
    console.error('Error deleting book:', err);
    res.status(500).json({ error: err.message });
  }
});

module.exports = router; 